package com.itheima.utils;

import com.itheima.pojo.User;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class Fiter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;

        String Url = req.getRequestURL().toString();
        //判断是否为登录请求
        if(Url.contains("/login")){
            chain.doFilter(request,response);
            return;
        }

        String Jwt = req.getHeader("token");
        if(!StringUtils.hasLength(Jwt)){
            log.info("token为空");
            res.setStatus(401);
        }

        try {
            //解析token
            Claims claims = TokenMaker.parseToken(Jwt);
            User userNow= (User)claims.get("user");
            User user = ThreadHolder.get();
            if (user==userNow){
                log.info("token解析成功ye");
                chain.doFilter(request,response);
                return;
            }
        }catch (Exception e){
            log.info("token解析失败");
            res.setStatus(401);
            return;
        }

        log.info("token解析成功");
        chain.doFilter(request,response);

    }
}
